package com.yzq.os.spider.v.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.yzq.os.spider.v.Constants;
import com.yzq.os.spider.v.domain.LogRecord;
import com.yzq.os.spider.v.service.domain.SpiderRecordService;
import com.yzq.os.spider.v.service.domain.LogRecordService;

/**
 * 运行日志控制器
 * 
 * @author 苑志强(xingyu_yzq@163.com)
 * 
 */
@Controller
@RequestMapping("/log")
public class LogRecordController {

	@Autowired
	private LogRecordService logRecordService;

	@Autowired
	private SpiderRecordService spiderRecordService;

	/**
	 * 查看运行日志
	 * @return
	 */
	@RequestMapping("/form")
	public ModelAndView form() {
		return new ModelAndView("/admin/log/form");
	}

	/**
	 * 通过抓取日期获取运行日志
	 * @param spiderDate
	 * @return
	 * @throws ParseException
	 */
	@RequestMapping(value = "/find", method = RequestMethod.POST)
	public ModelAndView find(String spiderDate) throws ParseException {
		Map<String, Integer> savedRecordCountCache = new HashMap<String, Integer>();
		Date date = DateUtils.parseDate(spiderDate,new String[] { Constants.DATE_PATTERN });
		List<LogRecord> logs = logRecordService.findBySpiderDate(date);
		if (CollectionUtils.isNotEmpty(logs)) {
			for (LogRecord log : logs) {
				int engineId = log.getSearchEngineId();
				Date startTime = log.getStartTime();
				String tableName = SpiderRecordService.parseTableName(
						engineId, startTime);
				Integer savedJobCount = savedRecordCountCache.get(tableName);
				if (savedJobCount == null) {
					savedJobCount = spiderRecordService.countOnlineTable(tableName);
					savedRecordCountCache.put(tableName, savedJobCount);
				}
				log.setSavedJobCount(savedJobCount);
			}
		}

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("spiderDate", spiderDate);
		model.put("logs", logs);
		return new ModelAndView("/admin/log/list", model);
	}
}
